<template>
  <div>
    <a-spin :spinning="loading">
      <a-form layout="vertical" class="operate-page-form" :model="formState" @validateFields="handleOk" ref="formRef" :rules="wipRule">
        <div class="operate-page-content-mo">
          <div>
            <div  class=' relative'>
              <div class=' mb-13 relative'>
                <div class="divTip1" >{{ $t('hangManage.newGuide') }}</div>
                <span class="blue-line">{{ $t('hangManage.productionInfo') }}</span>
              </div>
              <a-row :gutter="40">
                <a-col :span="6" v-if="!isEdit" class="relative">
                  <div class="div-tip-normal" >
                    {{ $t('other.selectMakeNoOrSection') }}
                    <div  class="point-mo"><span>1</span></div>
                  </div>
                  <a-form-item :label="$t('hangManage.makeNo')" name="moId">
                    <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="formState.moId" @change="onMakeChange" show-search :filter-option="filterOption" :class="{'single-border': !formState.moId}">
                      <a-select-option v-for="(item) in makeList" :key="`${item.moNo}-(${item.styleNo})`" :value="item.id">{{item.moNo}}-({{item.styleNo}})</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6"  class="relative">
                  <div class="div-tip-normal" v-if="isEdit">
                    {{ $t('other.selectMakeNoOrSection') }}
                    <div  class="point-mo"><span>1</span></div>
                  </div>
                  <a-form-item :label="$t('menu.basic:section')+':'" name="sectionId">
                    <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="formState.sectionId" :class="{'single-border': !formState.sectionId}">
                      <a-select-option v-for="item in sectionList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="6">
                  <a-form-item label="产品部位:" name="productPart">
                    <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="formState.productPart">
                      <a-select-option v-for="(item, index) in partList" :key="index" :value="item.productPart">{{item.productPart}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col> -->
                <a-col :span="6">
                  <a-form-item :label="$t('hangManage.lineDate')" name="produceOnlineTime">
                    <a-date-picker value-format="YYYY-MM-DD" v-model:value="formState.produceOnlineTime" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item :label="$t('basicData.styleNo')"  >
                    <a-input disabled v-model:value="styleNo"/>
                  </a-form-item>
                </a-col>
              </a-row>
              <MakeDetailTable ref="makeDetailTable" :isEdit="isEdit || isCopy" :tableData="makeTableData" :produceOnlineTime="formState.produceOnlineTime" />
              <div class='blue-line mb-13 pt-10 relative'>
                <div class="divTip3" >
                  {{ $t('other.selectRoadmapVersionAndSite') }}
                  <div  class="point-mo"><span>3</span></div>
                </div>
                {{ $t('hangManage.road') }}
              </div>
              <a-row :gutter="40">
                <a-col :span="6">
                  <a-form-item :label="$t('hangManage.roadVer')+':'" name="roadMapId">
                    <a-select :placeholder="$t('common.pleaseSelect')" v-model:value="formState.roadMapId" @change="onRoadChange" :class="{'single-border': !formState.roadMapId}">
                      <a-select-option v-for="item in roadList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item :label="$t('hangManage.hangerStation')+':'" name="stationIds">
                    <a-select :placeholder="$t('common.pleaseSelect')" multiline v-model:value="formState.stationIds" mode="multiple" allowClear :class="{'single-border': !formState.stationIds?.length}">
                      <a-select-option v-for="(item, key) in boltStationList" :key="key" :value="item.stationId">{{item.stationNo}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <RoadmapTable v-if="!formState.roadId" :dataSource="roadTableData" class="mb-20" />
            </div>
          </div>
        </div>

        <div class="operate-page-btns">
          <a-space>
            <a-button class="cancel" @click="closeTab">{{ $t('common.cancel') }}</a-button>
            <a-button @click="handleOk" type="primary" class="confirm">{{ $t('common.ok') }}</a-button>
          </a-space>
        </div>
      </a-form>
    </a-spin>
  </div>
</template>
<script setup name="operateWip">
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import MakeDetailTable from './makeDetailTable.vue'
import RoadmapTable from './roadmapTable.vue'
import { wipRule } from './wipConfig'
import { ref, computed, onMounted, nextTick } from 'vue'
import { store } from '@/store'
import axios from '@/utils/request'
import moment from 'moment'
import { cloneDeep, pick } from 'lodash'
import { getLocalStorage } from '@/utils'
import i18n from '@/locales/index'
const { t } = i18n.global
let loading = ref(false)
let formState = ref({})
const formRef = ref()
let isEdit = ref(false)
let isCopy = ref(false)
const route = useRoute()
const router = useRouter()
let roadTableData = ref([])
let makeTableData = ref([])
let roadList = ref([])
let boltStationList = ref([])
let makeDetailTable = ref()
let styleNo = ref()
// const partList = ref([])
let recordInfo = ref({})
const sectionList = computed(() => {
  return store.state.normalData.sectionList
})
const makeList = computed(() => {
  return store.state.normalData.makeList
})
const allMakeList = computed(() => {
  return store.state.normalData.allMakeList
})
const tabs = computed(() => {
  return store.state.setting.tabs
})
const filterOption = (input, option) => {
  return option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
const onMakeChange = async (value) => {
  // let selectInfo = makeList.value.filter(i => i.id === value)
  // initPart(selectInfo[0].productPartDTOList)
  if(!formState.value.sectionId && sectionList.value.length == 1) formState.value.sectionId = sectionList.value[0].id
  initPart()
  initRoad()
  await getMakeDetail(value)
  await getRoadOptions(value)
}
// const initPart = (list) => {
const initPart = () => {
  formState.value.productPart = undefined
  // partList.value = list
}

const initRoad = () => {
  formState.value.roadMapId = undefined
  formState.value.stationIds = []
  roadTableData.value = []
  boltStationList.value = []
}
const getMakeDetail = async (id) => {
  const res = await axios.getAction('/api/hanger/schedule-bill/get-schedulebill-mo-detail', { moId: id })
  makeTableData.value = res.success ? res.data : []
  styleNo.value = makeTableData.value[0]?.styleNo || ''
}

const getRoadOptions = async (id) => {
  const res = await axios.getAction('/api/mo/mo-proc-roadmap/get-roadmap-by-mo-id', { moId: id })
  roadList.value = res.success ? res.data : []
}

const onRoadChange = (value) => {
  formState.value.stationIds = []
  let selectInfo = roadList.value.filter(i => i.id === value)
  boltStationList.value = selectInfo[0].moStationVOList || []
  formState.value.stationIds = boltStationList.value.map(i=> i.stationId)
  getRoadDetail(value)
}

const getRoadDetail = async (id) => {
  const res = await axios.getAction('/api/mo/mo-proc-roadmap/get', { id })
  roadTableData.value = res.success ? res.data.moProcRoadmapProcList : []
}

const closeTab = async (isSuccess) => {
  const tabList = cloneDeep(tabs.value)
  let changeTabs = tabList.filter((i) => {
    if (isSuccess) {
      return !['/hangManage/wipInfo', route.path].includes(i.path)
    } else {
      return i.path !== route.path
    }
  })
  await store.commit('updateState', { tabs: changeTabs })

  router.replace({ path: '/hangManage/wipInfo' })
}

const getParams = (formValue) => {
  let params = { ...formValue }
  params.hangerLineId = getLocalStorage('currentLine') ? getLocalStorage('currentLine').id : null
  params.produceOnlineTime && (params.produceOnlineTime = moment(params.produceOnlineTime).valueOf())
  if (!isEdit.value) {
    let dataSource = makeDetailTable.value.dataSource.map(item => {
      let { overProduceQty, planFinishTime, produceQty, unit } = item
      return ({
        unit,
        produceQty,
        overProduceQty,
        moDetailId: item.id,
        planFinishTime: planFinishTime ? moment(planFinishTime).valueOf() : null
      })
    })
    params.detailAddVOList = dataSource
  } else {
    let dataSourceInfo = { ...makeDetailTable.value.dataSource[0] }
    dataSourceInfo.moDetailId = dataSourceInfo.id
    dataSourceInfo.planFinishTime = dataSourceInfo.planFinishTime ? moment(dataSourceInfo.planFinishTime).valueOf() : null
    Object.assign(params, dataSourceInfo)
    params.moId = recordInfo.value.moId
    params.stationIds = formValue.stationIds
    params.id = recordInfo.value.id
  }
  return params
}

const handleOk = async () => {
  try {
    await makeDetailTable.value.makeForm.validateFields()
    await formRef.value.validateFields()
    loading.value = true
    let url = isEdit.value ? '/api/hanger/schedule-bill/edit' : '/api/hanger/schedule-bill/add-batch'
    const res = await axios.postAction(url, getParams(formState.value))
    if (res.success) {
      message.success(res.msg || t('common.doSuccess'))
      closeTab(true)
    }
    loading.value = false
  } catch {
    loading.value = false
    console.log('err!!!!!~~~');
  }
}

const initOption = async (recordData) => {
  let listData = isEdit.value ? allMakeList.value : makeList.value
  let selectInfo = listData.filter(i => i.id === recordData.moId)
  if (!selectInfo.length) return
  // let productInfo = makeList.value.filter(i => i.id === selectInfo[0].id)
  // initPart(productInfo[0].productPartDTOList)
  initPart()
  await getRoadOptions(recordData.moId)
  await onRoadChange(recordData.roadMapId)
}

const initMakeTable = (recordData) => {
  let tableObj = pick(recordData, ['scheduleBillNo', 'moNo', 'styleNo', 'productType', 'poNo', 'cutterNo', 'tailorBill', 'color', 'size', 'quantity', 'assignedQty', 'unassignedQty', 'unit', 'produceQty', 'overProduceQty', 'planFinishTime'])
  tableObj.id = recordData.moDetailId
  tableObj.planFinishTime && (tableObj.planFinishTime = moment(tableObj.planFinishTime).format('YYYY-MM-DD'))
  // tableObj.planFinishTime && (tableObj.planFinishTime = '' + tableObj.planFinishTime)
  // 历史排产单复制 任务数量置空  不是0
  if (isCopy.value){
    tableObj.produceQty = null
  }
  makeTableData.value = [tableObj]
}

const initFormData = async () => {
  styleNo.value = ''
  let record = {}
  const recordData = recordInfo.value
  if (isEdit.value || isCopy.value) {
    await initOption(recordData)
    record = pick(recordData, ['sectionId', 'productPart', 'produceOnlineTime', 'roadMapId' ])
    if(isCopy.value) {
      record.moId = recordData.moId
    } else { 
      record.stationIds = recordData.stationIds || undefined
    }
    styleNo.value = recordData.styleNo
    initMakeTable(recordData)
  } else {
    record.produceOnlineTime = moment(new Date())
    let { moId, routeId } = route.query
    if (moId) {
      await onMakeChange(moId)
      record.moId = moId
      if (routeId) {
        onRoadChange(routeId)
        record.roadMapId = routeId
      }
    }
  }
  record.produceOnlineTime && (record.produceOnlineTime = moment(record.produceOnlineTime).format('YYYY-MM-DD'))
  await nextTick()
  formRef.value && formRef.value.resetFields()
  formState.value = cloneDeep(record)
}

const getWipDetail = async (id) => {
  try {
    const res = await axios.getAction('/api/hanger/schedule-bill/get', { id })
    if (res.success) recordInfo.value = res.data
  } catch {
    closeTab()
  }
}

onMounted(async () => {
  loading.value = true
  isEdit.value = route.path !== '/hangManage/wipInfo/add'
  isCopy.value = route.path === '/hangManage/wipInfo/add' && route.query.type == 'copy' 
  if ((isEdit.value || isCopy.value)&& !route.query.id) {
    closeTab()
    return
  }
  await store.dispatch('getAllMake')
  await store.dispatch('getMake')
  await store.dispatch('getSection')
  await store.dispatch('getPart')
  if (route.query.id) await getWipDetail(route.query.id)
  initFormData()
  loading.value = false
})
</script>
